package com.tao.filter;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tao.pojo.vo.LoginUser;
import com.tao.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/*
 * 全局新增修改拦截器
 * */
@Component
@Primary
public class GlobalMateObjectHandler implements MetaObjectHandler {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;

    private static final String TOKEN_HEADER = "token";
    private static final String REDIS_KEY_PREFIX = "login:";

    @Override
    public void insertFill(MetaObject metaObject) {

        Long id=null;
        // 获取用户名
        String token = request.getHeader(TOKEN_HEADER);
        if (!ObjectUtils.isEmpty(token)) {
            // 放行
            // 解析token
            String userId;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userId = claims.getSubject();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("Invalid token");
            }

            // 从redis中获取用户信息
            LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(REDIS_KEY_PREFIX + userId);
            assert loginUser != null;
            Object sortValue = metaObject.getValue("sort");
            if (sortValue == null || sortValue.toString().isEmpty()) {
                // sort属性为空
                // 执行初始化逻辑，设置初始值
                metaObject.setValue("sort", 100);
            }
            id = loginUser.getUser().getId();
        }

        metaObject.setValue("status", 1);
        metaObject.setValue("createBy", id);
        metaObject.setValue("updateBy", id);
        // 继续执行其他逻辑
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 获取用户名
        String token = request.getHeader(TOKEN_HEADER);

        Long id=null;
        // 获取用户名
        if (!ObjectUtils.isEmpty(token)) {
            // 放行
            // 解析token
            String userId;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userId = claims.getSubject();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("Invalid token");
            }

            // 从redis中获取用户信息
            LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(REDIS_KEY_PREFIX + userId);
            assert loginUser != null;
            Object sortValue = metaObject.getValue("sort");
            if (sortValue == null || sortValue.toString().isEmpty()) {
                // sort属性为空
                // 执行初始化逻辑，设置初始值
                metaObject.setValue("sort", 100);
            }
            id = loginUser.getUser().getId();
            metaObject.setValue("updateBy", id);
        }

        metaObject.setValue("updateTime", LocalDateTime.now());

    }
}
